import React, { useState } from 'react';
import { Form, Input, DatePicker, Button, message } from 'antd';
import { useParams, useNavigate } from 'react-router-dom';
import './Apply.css';
import moment from 'moment';
import axios from '../axios';
import userStore from '../stores/UserStore';

const Apply = () => {
    const { petId } = useParams();
    const [form] = Form.useForm();
    const navigate = useNavigate();

    const onFinish = (values) => {

        const finalValues = { ...values, petId };
        console.log('提交的申请信息:', finalValues);
        const userId = userStore.getUser().id;
        // 提取现有属性
        const keys = Object.keys(finalValues);
        const valuesArray = keys.map(key => finalValues[key]);

        // 在第三个位置插入 userId
        keys.splice(2, 0, 'adoptUserId');
        valuesArray.splice(2, 0, userId);

        // 创建新对象
        const dataToSend = {};
        keys.forEach((key, index) => {
            dataToSend[key] = valuesArray[index];
        });

        axios.post('/users/apply', dataToSend, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => { // 注意这里接收的是 response 对象
            if (response.data.code === 2000) { // 使用 response.data 访问返回的数据
                message.success('申请提交成功！');
                navigate('/AdoptCenter');
            } else {
                message.error('申请提交失败，请重试！');
            }
        })
        .catch(error => {
            console.error('提交申请时出错:', error);
            message.error('申请提交时出错，请重试！');
        });
    };

    const onFinishFailed = (errorInfo) => {
        console.log('表单提交失败:', errorInfo);
        message.error('表单填写有误，请检查！');
    };

    return (
        <div className="apply-page">
            <div className="apply-content">
                <h2 className="apply-title">宠物领养申请表</h2>
                <Form
                    // 将 form 实例传递给 Form 组件
                    form={form}
                    name="adoptionForm"
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    initialValues={{
                        applicant_name: '',
                        adopt_email: '',
                        adopt_phone: '',
                        adopt_address: '',
                        adopt_date: null,
                        adopt_reason: ''
                    }}
                    scrollToFirstError
                    className="apply-form"
                >
                    <Form.Item
                        name="applicant_name"
                        rules={[
                            {
                                required: true,
                                message: '请输入申请人姓名！'
                            },
                            {
                                min: 2,
                                max: 20,
                                message: '姓名长度应在 2 到 20 之间！'
                            }
                        ]}
                    >
                        <Input
                            placeholder="申请人姓名"
                        />
                    </Form.Item>
                    <Form.Item
                        name="adopt_email"
                        rules={[
                            {
                                required: true,
                                message: '请输入申请人邮箱！'
                            },
                            {
                                type: 'email',
                                message: '请输入有效的邮箱地址！'
                            }
                        ]}
                    >
                        <Input
                            placeholder="申请人邮箱"
                        />
                    </Form.Item>
                    <Form.Item
                        name="adopt_phone"
                        rules={[
                            {
                                required: true,
                                message: '请输入申请人电话！'
                            },
                            {
                                pattern: /^1[3-9]\d{9}$/,
                                message: '请输入有效的手机号码！'
                            }
                        ]}
                    >
                        <Input
                            placeholder="申请人电话"
                        />
                    </Form.Item>
                    <Form.Item
                        name="adopt_address"
                        rules={[
                            {
                                required: true,
                                message: '请输入申请人地址！'
                            }
                        ]}
                    >
                        <Input
                            placeholder="申请人地址"
                        />
                    </Form.Item>
                    <Form.Item
                        name="adopt_date"
                        rules={[
                            {
                                required: true,
                                message: '请选择领养日期！'
                            }
                        ]}
                    >
                        <DatePicker
                            placeholder="领养日期"
                            format="YYYY-MM-DD"
                            value={form.getFieldValue('adopt_date') ? moment(form.getFieldValue('adopt_date'), 'YYYY-MM-DD') : null}
                        />
                    </Form.Item>
                    <Form.Item
                        name="adopt_reason"
                        rules={[
                            {
                                required: true,
                                message: '请输入领养原因！'
                            }
                        ]}
                    >
                        <Input.TextArea
                            placeholder="领养原因"
                        />
                    </Form.Item>
                    <Form.Item className="apply-form-buttons">
                        <Button
                            type="primary"
                            htmlType="submit"

                        >
                            提交申请
                        </Button>
                        <Button
                            onClick={() => form.resetFields()}
                        >
                            重置表单
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Apply;